package com.xq.springboot.controller;

import com.xq.springboot.common.ActiverUser;
import com.xq.springboot.pojo.User;
import com.xq.springboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author xq
 * @version 1.0
 * @date 2021/4/19 8:48
 * @description
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param userName 用户名
     * @param password 密码
     * @param session 会议作用域对象
     * @return
     */
    @RequestMapping("login")
    public String login(String userName, String password, HttpSession session) {
        // 创建token
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        // 创建主体
        Subject subject = SecurityUtils.getSubject();
        try {
            // 登录认证
            subject.login(token);
            // 登录成功，获取subject中ActiverUser对象
            ActiverUser activerUser = (ActiverUser)subject.getPrincipal();
            // 将activerUser对象中的user对象保存到session作用域中
            session.setAttribute("user",activerUser.getUser());
            // 登录成功跳转到用户管理
            return "redirect:/user/toUserManager";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            // 登录认证不成功，跳转到index.html
            return "redirect:/index.html";
        }
    }

    /**
     * 跳转到用户管理
     * @return
     */
    @RequestMapping("toUserManager")
    public String toUserManager() {
        return "list";
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping("addUser")
    public String addUser(User user) {
        this.userService.insert(user);
        return "redirect:/index.html";
    }

}
